const express = require("express")
const mongoose = require("mongoose")
//const mongodb = require("mongodb")
const bodyParser = require("body-parser")
const passport = require("passport")
const app = express()

// 解决跨区域问题
// 导入中间件 cors
const cors = require('cors');
// 在路由之前调用app.use(cors())配置中间件
app.use(cors());
app.all("*", (req, res, next) => {
  res.header("Acess-Control-Allow-Origin", "*");
  next();
})

//引入users.js
const users = require("./routes/api/users")
const profiles = require("./routes/api/profiles")
const mapdata = require("./routes/api/mapdata")
const linechart = require("./routes/api/linechart")
const adopters = require("./routes/api/adopters")

// DB config
const db = require("./config/keys").mongoURI

//使用body-parser中间件
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())


// Connect to mongodb
mongoose.connect(db)
        .then(()=> console.log("MongoDB Connected"))
        .catch(err=>console.log(err))

//passport初始化
app.use(passport.initialize())

require("./config/passport")(passport)

// app.get("/",(req,res) => {
//     res.send("Hello World")
// })

app.use(express.static('public'))

//使用routes
app.use("/api/users",users)
app.use("/api/profiles",profiles)
app.use("/api/mapData",mapdata)
app.use("/api/linechart",linechart)
app.use("/api/adopters",adopters)

const port = process.env.PORT || 5000

app.listen(port,() => {
    console.log(`Server running on port ${port}`);
})